<?php

namespace Xehang\Enum;

use Xehang\Enum\Exceptions\MissingEnumCaptionException;

abstract class Enum
{
    /**
     * @var array A cache of all enum values to increase performance
     */
    protected static $cache = array();

    /**
     * Returns the values of all of constants
     *
     * @return array
     */
    public static function getValues()
    {
        return array_values(static::getAssoc());
    }

    /**
     * Returns the values and captions of all the constants
     *
     * @return array
     */
    abstract public static function getCaptions();

    /**
     * Returns the caption of given enum value
     *
     * @return string
     */
    public static function getCaption($value)
    {
        $captions = static::getCaptions();

        if (!isset($captions[$value])) {
            $class = get_called_class();
            throw new MissingEnumCaptionException("please add a caption for the value: $value in class: $class");
        }

        return $captions[$value];
    }

    /**
     * Return the keys and values of all the constants
     *
     * @return array
     */
    public static function getAssoc()
    {
        $class = get_called_class();

        if (!isset(self::$cache[$class])) {
            $reflected = new \ReflectionClass($class);
            self::$cache[$class] = $reflected->getConstants();
        }

        return self::$cache[$class];
    }
}
